<?php 
/**
* @name Maiji
* @author pd87@qq.com
* @copyright m-j.cc
* @version v1.0
*/

/* 
	错误提示页面
	$msg 消息
	$url 跳转链接
	$wait 提示时间
 */
function error($msg,$url='javascript:history.back(-1);',$wait=3){
	_ini_jump(0,$msg,$url,$wait);
}
/* 
	成功提示页面
	$msg 消息
	$url 跳转链接
	$wait 提示时间
 */
function success($msg,$url='javascript:history.back(-1);',$wait=3){
	_ini_jump(1,$msg,$url,$wait);
}

/* 
	提示模板
 */
function _ini_jump($code,$msg,$url='javascript:history.back(-1);',$wait=3){
	ob_end_clean(); //清除输出缓冲
	die(include_once(APP_INI_PATH.'tpl/dispathc_jump.tpl'));
}

/*
 * 下划线转驼峰
 */
function convertUnderline($str)
{
    $str = preg_replace_callback('/([-_]+([a-z]{1}))/i',function($matches){
        return strtoupper($matches[2]);
    },$str);
    return $str;
}

/*
 * 驼峰转下划线
 */
function humpToLine($str){
    $str = preg_replace_callback('/([A-Z]{1})/',function($matches){
        return '_'.strtolower($matches[0]);
    },$str);
    return $str;
}

function convertHump(array $data){
    $result = [];
    foreach ($data as $key => $item) {
        if (is_array($item) || is_object($item)) {
            $result[$this->humpToLine($key)] = $this->convertHump((array)$item);
        } else {
            $result[$this->humpToLine($key)] = $item;
        }
    }
    return $result;
}

/**
 * 循环创建文件夹
 */
function createFolders($dir) {
    return is_dir($dir) or ( createFolders(dirname($dir)) and mkdir($dir, 0777));
}

/**
 * 读取POST值
 */
function POST($name='.') {
    if(isset($_POST[$name])){
		foreach($_POST as $a => $c){
			if(is_array($c)){
				foreach($c as $aa => $cc){
					$data[$a][$aa] = htmlspecialchars(GUOLV(trim($cc)));
				}
			}else{
				$data[$a] = htmlspecialchars(GUOLV(trim($c)));
			}
		}
        $value = $data[$name];
        return $value;
    }elseif($name == '.'){
		return $_POST;
	}else{
		return null;
	}
}

/**
 * GET请求
 */
function GET($name='.') {
    if(isset($_GET[$name])){
        $value = $_GET[$name];
    }elseif($name == '.'){
        $value = $_GET;
    }else{
        $value = null;
    }
    return $value;
}

/**
 * 读取配置文件
 */
function C($name = ''){
	global $_CONFIG;
	if(empty($name)){
		return $_CONFIG;
	}else{
		$_ls = explode('.',$name);
		if(count($_ls) > 1){
			$b = $_CONFIG;
			foreach($_ls as $a){
				if(!isset($b[$a])){
					return null;
				}else{
					$b = $b[$a];
				}
			}
			return $b;
		}else{
			return $_CONFIG[$_ls[0]];
		}
	}
}

/**
 * 获取ip
 */
function GETIP() { 
	if(getenv('HTTP_CLIENT_IP')){
		$ip = getenv('HTTP_CLIENT_IP');
	}elseif(getenv('HTTP_X_FORWARDED_FOR')){
		$ip = getenv('HTTP_X_FORWARDED_FOR');
	}elseif(getenv('HTTP_X_FORWARDED')){
		$ip = getenv('HTTP_X_FORWARDED');
	}elseif(getenv('HTTP_FORWARDED_FOR')){
		$ip = getenv('HTTP_FORWARDED_FOR');
	}elseif(getenv('HTTP_FORWARDED')){
		$ip = getenv('HTTP_FORWARDED');
	}else{
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	return$ip;
}
/**
 * get请求
 */
function HTTPGET($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL, $url);
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
}

/**
 * post请求
 */
function HTTPPOST($url,$data,$type = ''){ // 模拟提交数据函数      
    $curl = curl_init(); // 启动一个CURL会话      
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
	if($type == 'json'){
		curl_setopt($curl,CURLOPT_HTTPHEADER,array('Content-Type: application/json; charset=utf-8'));
	}
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查      
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在      
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器      
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转      
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer      
    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求      
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包      
    curl_setopt($curl, CURLOPT_COOKIEFILE, $GLOBALS['cookie_file']); // 读取上面所储存的Cookie信息      
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环      
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容      
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回      
    $tmpInfo = curl_exec($curl); // 执行操作      
    if (curl_errno($curl)) {      
       echo 'Errno'.curl_error($curl);      
    }      
    curl_close($curl); // 关键CURL会话      
    return $tmpInfo; // 返回数据      
}
/**
 *调试输出
 */
function dump(){ 
	$args=func_get_args();
	if(count($args)<1){
		echo("<fontcolor='red'>Debug");
		return;
	}
	echo '<div style="width:100%;text-align:left"><pre>';
	foreach($args as $arg){
		if(is_array($arg)){  
			var_dump($arg);
			echo '<br>';
		}elseif(is_string($arg)){
			var_dump($arg);
			echo '<br>';
		}else{ 
			var_dump($arg);
			echo '<br>';
		}
	}
	echo '</pre></div>';
}

/**
 * 去除PHP代码注释
 * @param string $content 代码内容
 * @return string 去除注释之后的内容
 */
function strip_whitespace($content) {
    $stripStr = '';
    //分析php源码
    $tokens =   token_get_all ($content);
    $last_space = false;
    for ($i = 0, $j = count ($tokens); $i < $j; $i++){
        if (is_string ($tokens[$i])){
            $last_space = false;
            $stripStr .= $tokens[$i];
        }
        else{
            switch ($tokens[$i][0]){
                //过滤各种PHP注释
                case T_COMMENT:
                case T_DOC_COMMENT:
                    break;
                //过滤空格
                case T_WHITESPACE:
                    if (!$last_space){
                        $stripStr .= ' ';
                        $last_space = true;
                    }
                    break;
                default:
                    $last_space = false;
                    $stripStr .= $tokens[$i][1];
            }
        }
    }
    return $stripStr;
}
/**
 * 插件编译
 */
function RUN_CHACHE($caching = 'true'){
	$_ls1 = glob(APP_INI_PATH."libs/*");
	$_ls2 = glob(APP_SYS_PATH."plugins/*");
	$ls = array_merge($_ls1,$_ls2);
	$dm = null;
	if(is_dir(APP_CACHE_PATH)){
		$dir = APP_CACHE_PATH.'~runtime.php';
	}else{
		createFolders(APP_CACHE_PATH);
		$dir = APP_CACHE_PATH.'~runtime.php';
	}
	if(!empty($ls)){
		if($caching == 'true'){
			if(file_exists($dir)){
				include_once($dir);
				return true;
			}else{
				foreach($ls as $a){
					if(substr($a,-4) == '.php'){
						$dm .= file_get_contents($a);
					}
				}
				$dm = strip_whitespace($dm);
				$dm = str_replace('<?php','',$dm);
				$file = fopen($dir,'w');
				fwrite($file,'<?php'.$dm);
				fclose($file);
				include_once($dir);
				return true;
			}
		}else{
			foreach($ls as $a){
				if(substr($a,-4) == '.php'){
					include_once($a);
				}
			}
			return true;
		}
	}else{
		return false;
	}
}
 
/**
 * 获取当前页面完整URL地址
 */
function GET_URL() {
  $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
  $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
  $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
  $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
  return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
}

/**
 * 获取当前请求URL地址
 */
function REQUEST_URL(){
	if(isset($_SERVER['argv'])){
		$uri = $_SERVER['PHP_SELF'].(empty($_SERVER['argv']) ? '' : ('?'.$_SERVER['argv'][0]));
	}elseif(isset($_SERVER['QUERY_STRING'])){
		$uri = $_SERVER['PHP_SELF'].(empty($_SERVER['QUERY_STRING']) ? '' : ('?'.$_SERVER['QUERY_STRING']));
	}elseif(isset($_SERVER['REQUEST_URI'])){
		$uri = $_SERVER['REQUEST_URI'];
	}else{
		$uri = $_SERVER['PHP_SELF'].(empty($_SERVER['QUERY_STRING']) ? '' : ('?'.$_SERVER['QUERY_STRING']));
	}
	$uri = $_SERVER['PHP_SELF'].(empty($_SERVER['QUERY_STRING']) ? '' : ('?'.$_SERVER['QUERY_STRING']));
	return ltrim(strtolower(urldecode(trim($uri))),'/');
}

/**
*过滤GET请求
*/
function MAIJI_URL_GET(){
	if(C('mysql.MYSQL_PREFIX')){
		$get = array('<','>','..','(',')','"',"'","*",'[',']','{','}',';','$',C('mysql.MYSQL_PREFIX'),'%','#');
	}else{
		$get = array('<','>','..','(',')','"',"'","*",'[',']','{','}',';','$','%','#');
	}
	$url = REQUEST_URL();
	// 过滤特殊字符
	foreach($get as $a){
		if(strpos($url,$a) !== false){
			return false;
		}
	}
	// 过滤反斜杠
	if(!empty($_GET) && isset($_GET)){
		foreach($_GET as $a => $b){
			$_GET[$a] = stripslashes($b);
		}
	}
	return true;
}

/**
 *过滤POST请求
 */
function MAIJI_URL_POST(){
	if(isset($_POST) && $_POST){
		if(!empty(C('mysql.MYSQL_PREFIX'))){
			if(strstr(json_encode($_POST),C('mysql.MYSQL_PREFIX'))){
				return false;
			}
		}
		return true;
	}else{
		return true;
	}
}

/**
 *guolv
 */
function GUOLV($val){
	$val = trim($val);
	$val = str_replace("'",'',$val);
	$val = str_replace("..",'',$val);
	$val = str_replace('%','',$val);
	$val = str_replace('#','',$val);
	$val = str_replace('*','',$val);
	$val = str_replace(chr(32),'',$val);
	$val = str_replace(chr(9),'',$val);
	$val = str_replace(chr(9),'',$val);
	$val = str_replace(chr(34),'',$val);
	$val = str_replace(chr(39),'',$val);
	$val = str_replace(chr(13),'
	',$val);
	// html
	$val = str_replace("&", "&amp;", $val);
	$val = str_replace(">", "&gt;", $val);
	$val = str_replace("<", "&lt;", $val);
	$val = str_replace(chr(34), "&", $val);
	$val = str_replace(chr(39), "&#39;", $val);
	$val = str_replace(chr(13), "<br />", $val);
	$val = str_replace("'", "''", $val);
	$val = str_replace("select", "sel&#101;ct", $val);
	$val = str_replace("join", "jo&#105;n", $val);
	$val = str_replace("union", "un&#105;on", $val);
	$val = str_replace("where", "wh&#101;re", $val);
	$val = str_replace("insert", "ins&#101;rt", $val);
	$val = str_replace("delete", "del&#101;te", $val);
	$val = str_replace("update", "up&#100;ate", $val);
	$val = str_replace("like", "lik&#101;", $val);
	$val = str_replace("drop", "dro&#112;", $val);
	$val = str_replace("create", "cr&#101;ate", $val);
	$val = str_replace("modify", "mod&#105;fy", $val);
	$val = str_replace("rename", "ren&#097;me", $val);
	$val = str_replace("alter", "alt&#101;r", $val);
	$val = str_replace("cast", "ca&#115;", $val);
	$val = str_replace("and", "a&#110;d", $val);
	$val = str_replace("or", "o&#114;", $val);
	$val = str_replace("\\", "&#92;", $val);
	$val = str_replace("=", "&#61;", $val);
	$val = str_replace("+", "&#43;", $val);
	$val = str_replace("/*", "&#47;*", $val);
	$val = str_replace("*/", "*&#47;", $val);
	$val = str_replace("src", "s&#114;c", $val);
	$val = str_replace("script", "sc&#114;ipt", $val);
	$val = str_replace("%a0", "%&#97;0", $val);
	$val = str_replace("%00", "%&#48;0", $val);
	$val = str_replace("0x", "0&#120;", $val);
	$val = str_replace("offset", "off&#115;et", $val);
	$val = str_replace("ascii", "as&#99;ii", $val);
	return $val;
}

/**
 *json返回
 *$code 返回代码
 *$msg 返回消息
 *$icon 返回错误号 0.感叹号(!) 1.正确(√) 2.错误(×) 3.问号(?) 4.锁(锁) 5.苦脸 6.笑脸
 *$data 返回数据
 */
function json($code,$msg,$icon = 0,$data = []){
	return json_encode(array('code' => $code,'msg' => $msg,'icon' => $icon,'data' => $data));
}

// 依赖库处理
function Composer_run(){
	if(!file_exists(APP_SYS_PATH.'composer.json')){
		$content = "{
	\"require\": {
	}
}";
		$file = APP_SYS_PATH."composer.json";
		file_put_contents($file,$content,FILE_APPEND);
	}
	if(!file_exists(APP_SYS_PATH."vendor/")){
		createFolders(APP_SYS_PATH."vendor/");
		if(file_exists(APP_SYS_PATH."vendor/autoload.php")){
			// 依赖库
			require_once(APP_SYS_PATH."vendor/autoload.php");
		}
		$_hj = strtoupper(substr(PHP_OS,0,3))==='WIN'?true:false;
		if($_hj === true){
			if(!file_exists(APP_SYS_PATH.'composer.phar')){
				exec("cd ".APP_SYS_PATH,$val);
				exec(substr(APP_SYS_PATH,0,2),$val);
				$sys_path = substr(APP_SYS_PATH,0,-1);
				$_ml = [
					"php -r \"copy('https://install.phpcomposer.com/installer', '".$sys_path."\composer-setup.php');\"",
					"php ".$sys_path."\composer-setup.php",
					"php -r \"unlink('".$sys_path."\composer-setup.php');\"",
					"move ".substr(APP_RUN_PATH,0,-1)."\composer.phar ".$sys_path."",
					"php ".$sys_path."\composer.phar config -g repo.packagist composer https://packagist.phpcomposer.com",
				];
				foreach($_ml as $v => $a){
					if(file_exists(APP_SYS_PATH.'composer.phar') && $v <= 4){
						continue;
					}
					exec($a,$val);
				}
			}
		}else{
			
		}
	}
}


/**
 *路由当前url
 *返回数组
 *文件夹		0
 *文件			1
 *方法名		2
 */
function RUN_URL(){
	$page = null;
	$URL = null;
	if(C('basic.Composer')){
		Composer_run();
	}
	$_ls = RUN_CHACHE(C('basic.cache'));
	if($_ls == false){
		die(MAIJI\APP_Error::display('插件压缩失败！','系统错误，找作者'));
	}
	$_ls = MAIJI_URL_GET();
	if($_ls == false){
		die(MAIJI\APP_Error::display('请勿提交非法参数！','$_GET请求</br>'));
	}
	$_ls = MAIJI_URL_POST();
	if($_ls == false){
		die(MAIJI\APP_Error::display('请勿提交非法参数！','$_POST请求</br>'));
	}
	if(isset($_SERVER['PATH_INFO'])){
		$page = explode('.',substr($_SERVER['PATH_INFO'],1))[0];
		$page = explode('-',$page);
		unset($page[0]);
		$page = array_values($page);
		$URL = $_SERVER['PATH_INFO'];
	}elseif(isset($_SERVER['REDIRECT_URL'])){
		$page = explode('.',substr($_SERVER['REDIRECT_URL'],1))[0];
		$page = explode('-',$page);
		unset($page[0]);
		$page = array_values($page);
		$URL = $_SERVER['REDIRECT_URL'];
	}else{
		$_ls = explode('?',REQUEST_URL())[0];
		$_ls = explode('/',$_ls);
		if(isset($_ls[1])){
		    unset($_ls[0]);
		    $_ls = array_values($_ls);
		    $_ls = implode('/',$_ls);
			$URL = $_ls;
		}else{
			$URL = 'index.php';
		}
	}
	if(file_exists(APP_PATH.'route.php')){
		$route = include APP_PATH.'route.php';
		if($route){
			if(isset($route[substr($URL,1)])){
				$URL = $route[substr($URL,1)];
			}else{
				$_ls = explode('.',$URL);
				if($_ls){
					$file['type'] = isset($_ls[1]) ? $_ls[1] : null;
					$file['path'] = isset($_ls[0]) ? $_ls[0] : null;
				}
				if($file['path']){
					$file['file_path'] = explode('/',$file['path']);
				}
				$_ls = isset($file['file_path'][1]) ? $file['file_path'][1] : null;
				if(isset($route[$_ls]) && $route[$_ls]){
					$_ls2 = isset($route[$_ls]) ? $route[$_ls] : null;
					$URL = str_replace('/','-',$URL);
					$URL = str_replace('.','-',$URL);
					$URL = str_replace($_ls,$_ls2,$URL);
					$URL = '/'.substr($URL,1);
					$page = explode('.',substr($URL,1))[0];
					$page = explode('-',$page);
					unset($page[0]);
					$page = array_values($page);
				}
			}
		}
	}
	$der = explode('.',$URL)[0];
	$der = explode('-',$der);
	$der = explode('/',$der[0]);
	if($der[0] == 'index.php' || empty($der[0])){
		unset($der[0]);
	}
	if(in_array('public',$der)){
		foreach($der as $a => $c){
			if($c == 'public'){
				unset($der[$c]);
			}
		}
	}
	$der = array_values($der);
	if(count($der) == 0){
		Array_unshift($der,'index');
		Array_unshift($der,'index');
		Array_unshift($der,'index');
	}elseif(count($der) == 1){
		$_ls = explode('/',C('basic.route_path'));
		if(C('basic.route')){
			array_push($der,$_ls[0]);
			array_push($der,$_ls[1]);
		}else{
			Array_unshift($der,$_ls[1]);
			Array_unshift($der,$_ls[0]);
		}
	}elseif(count($der) == 2){
		$_ls = explode('/',C('basic.route_path'));
		if(C('basic.route')){
			array_push($der,$_ls[0]);
		}else{
			Array_unshift($der,$_ls[0]);
		}
	}
	if(is_array($page)){
		$der['page'] = $page;
	}else{
		$der['page'] = null;
	}
	foreach($der as $c => $a){
		if(empty($a) && $c != 'page'){
			$der[$c] = 'index';
		}
	}
	return $der;
}